package com.dcyao.musicserve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dcyao.musicserve.common.R;
import com.dcyao.musicserve.domain.Admin;
import com.dcyao.musicserve.domain.dto.AdminDTO;
import com.dcyao.musicserve.mapper.AdminMapper;
import com.dcyao.musicserve.service.AdminService;
import com.dcyao.musicserve.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

import static com.dcyao.musicserve.common.Constants.SALT;

@Service
public class AdminServiceImp extends ServiceImpl<AdminMapper, Admin> implements AdminService  {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public R verityPasswd(AdminDTO adminRequest) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminRequest.getUsername());
        // md5
        String secretPassword = DigestUtils.md5DigestAsHex((SALT + adminRequest.getPassword()).getBytes(StandardCharsets.UTF_8));
        queryWrapper.eq("password", secretPassword);
        Admin one = getOne(queryWrapper);
        if(one != null) {
            // 拷贝对象属性
            BeanUtil.copyProperties(one, adminRequest, true);
            String token = TokenUtils.genToken(one.getId().toString(), one.getPassword());
            adminRequest.setToken(token);
            return R.success("登录成功", adminRequest);
        }else {
            return R.error(400,"登录失败");
        }
    }

    @Override
    public R addUser(AdminDTO registryRequest) {
        if(existUser(registryRequest.getUsername())) {
            return R.error(400, "用户名已经注册");
        }
        Admin admin = new Admin();
        admin.setUsername(registryRequest.getUsername());
        // 开始加密
        String password = DigestUtils.md5DigestAsHex((SALT + registryRequest.getPassword()).getBytes(
                        StandardCharsets.UTF_8
                ));
        admin.setPassword(password);
        admin.setAvatar("img/user.jpg");
        if(adminMapper.insert(admin) > 0) {
            return R.success("注册成功");
        }else {
            return R.error(400,"注册失败");
        }
    }

    @Override
    public boolean existUser(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return adminMapper.selectCount(queryWrapper) > 0;
    }
}
